package commInterface

import (
	"encoding/json"
	"goAdapter/setting"
	"goAdapter/utils"
	"os"
	"strings"
)

type IoOutInterfaceParam struct {
	Name string   `json:"Name"`
	FD   *os.File `json:"-"`
}

type CommunicationIoOutTemplate struct {
	Name  string              `json:"Name"`  //接口名称
	Type  string              `json:"Type"`  //接口类型,比如serial,IoOut,udp,http
	Param IoOutInterfaceParam `json:"Param"` //接口参数
}

var CommunicationIoOutMap = make([]*CommunicationIoOutTemplate, 0)

func (c *CommunicationIoOutTemplate) Open() bool {

	fd, err := os.OpenFile(c.Param.Name, os.O_RDWR, 0666)
	if err != nil {
		setting.ZAPS.Errorf("通信接口[开关量输出][%s]打开失败 %v", c.Param.Name, err)
		return false
	}
	setting.ZAPS.Debugf("通信接口[开关量输出][%s]打开成功", c.Param.Name)
	c.Param.FD = fd

	return true
}

func (c *CommunicationIoOutTemplate) Close() bool {

	if c.Param.FD != nil {
		err := c.Param.FD.Close()
		if err != nil {
			setting.ZAPS.Errorf("通信接口[开关量输出][%s]关闭失败 %v", c.Param.Name, err)
			return false
		}
		setting.ZAPS.Debugf("通信接口[开关量输出][%s]关闭成功", c.Param.Name)
	}

	return true
}

func (c *CommunicationIoOutTemplate) WriteData(data []byte) int {

	if c.Param.FD != nil {
		if len(data) > 0 {
			_, err := c.Param.FD.Write(data)
			if err != nil {
				setting.ZAPS.Errorf("通信接口[开关量输出][%s]写入失败 %v", c.Param.Name, err)
			}
		}
		return 0
	}
	return 0
}

func (c *CommunicationIoOutTemplate) ReadData(data []byte) int {

	return 0
}

func (c *CommunicationIoOutTemplate) GetName() string {
	return c.Name
}

func (c *CommunicationIoOutTemplate) GetTimeOut() string {
	return ""
}

func (c *CommunicationIoOutTemplate) GetInterval() string {
	return ""
}

func (c *CommunicationIoOutTemplate) GetType() int {
	return CommTypeIoOut
}

func (c *CommunicationIoOutTemplate) GetTypeName() string {
	return c.Type
}

func (c *CommunicationIoOutTemplate) GetParam() ComInterfaceParam {
	var para ComInterfaceParam
	para.IoOutParam = c.Param
	return para
}

func (c *CommunicationIoOutTemplate) GetParamString() string {

	return ""
}

func ReadCommIoOutInterfaceListFromJson() bool {

	data, err := utils.FileRead("/selfpara/commIoOutInterface.json")
	if err != nil {
		if strings.Contains(err.Error(), "no such directory") {
			setting.ZAPS.Debug("打开通信接口[开关量输出]配置json文件失败")
		} else {
			setting.ZAPS.Debugf("打开通信接口[开关量输出]配置json文件失败 %v", err)
		}

		return false
	}
	err = json.Unmarshal(data, &CommunicationIoOutMap)
	if err != nil {
		setting.ZAPS.Errorf("通信接口[开关量输出]配置json文件格式化失败 %v", err)
		return false
	}
	setting.ZAPS.Debugf("通信接口[开关量输出]配置json文件格式化成功")
	return true
}

func WriteCommIoOutInterfaceListToJson() {

	utils.DirIsExist("./selfpara")

	sJson, _ := json.Marshal(CommunicationIoOutMap)
	err := utils.FileWrite("/selfpara/commIoOutInterface.json", sJson)
	if err != nil {
		setting.ZAPS.Errorf("写入通信接口[开关量输出]配置json文件 %s %v", "失败", err)
		return
	}
	setting.ZAPS.Infof("写入通信接口[开关量输出]配置json文件 %s", "成功")
}
